﻿using System;
using System.Net;
using System.Windows;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using MiruPublic;

namespace MangaKurosagi
{
    public class DownloadStories
    {
        private StoriesOffline Temp=new StoriesOffline();

        public void DownloadStorie(Stories stori)
        {
            string filename = Utils.GetFileName(stori.UrlImage);

            StorageHelper.saveImage(filename, stori.UrlImage);

            stori.UrlImage = filename;

            Temp=StoriesOffline.Convert(stori,new List<ChapOffline>());

            DownloadChap();
        }
        private void DownloadChap()
        {
            LeadChap client = new LeadChap();

            client.DownLoadURL(Temp.Url);

            client.ListUpdateSucess += (s, args) =>
            {
                foreach (ItemChap Item in args.listResult)
                {
                    ChapOffline chap = new ChapOffline() { index = Item.index, Title = Item.Title, Url = Item.Url };

                    Temp.lsChap.Add(chap);

                    chap.lsImage=DownloadImageChap(Item.Url);
                }
                Global.ListDownload.Add(Temp);
            };
        }
        private List<string> DownloadImageChap(string url)
        {
            Website client = new Website();

            List<string> result=new List<string>();

            client.DownLoadURL(url);

            client.DownLoadCompleted += (s, args) =>
            {
                result=SaveImageChap(Utils.GetStringBetweenText(args.Result, "<div class=\"noidungchap\">", "</div>"));
            };
            return result;
        }
        private List<string> SaveImageChap(string content)
        {
            List<string> result = new List<string>();
            string CheckContent = content;
            string line = "";
            line = Utils.GetStringBetweenText(CheckContent, "<img src=\"", "\"");
            while (line != "")
            {

                string filename = Utils.GetFileName(line);

                StorageHelper.saveImage(filename, line);

                result.Add(filename);

                CheckContent = Utils.GetStringBetweenText(CheckContent, line, "");

                line = Utils.GetStringBetweenText(CheckContent, "<img src=\"", "\"");
            }
            return result;
        }
    }
}
